﻿<link href="@Url.Content("/content/styles/order.css")" rel="stylesheet" type="text/css" />

<div class="ld-tabs">
    <ul>
        <li class="k-state-active">填写新的 @LuxDiner.Web.Management.Common.GetOrderName(ViewBag.Method)</li>
    </ul>
    <div>
        <div class="k-block form_title">
            <div>
                <b>客户：</b><input id="txtCustomer" data-value="0" style="width: 400px" />
                <b>日期：</b><input id="txtNoteDate" />
            </div>
            <div style="margin-top:10px;">
                 <b>备注：</b><input type="text" class="k-textbox" id="txtDescription" style="width: 90%" />
            </div>
        </div>
        @if (ViewBag.Method == (int)LuxDiner.Model.Orders.OrderMethod.XS)
        {
            <div class="k-block form_title">
                <b>收货地址：</b><input type="text" class="k-textbox" id="txtAddress" style="width: 300px" />
                <b>收货人：</b><input type="text" class="k-textbox" id="txtRealName" />
                <b>联系手机：</b><input type="text" class="k-textbox" id="txtMobile" />
            </div>
        }
        <div id="grid_orders"></div>
        <table class="tbsum">
            <tr>
                <td style="width: 296px"></td>
                <td style="width: 295px;">&nbsp;&nbsp;总金额：<span id="lblSum"></span></td>
                <td>&nbsp;</td>
            </tr>
        </table>
    </div>
</div>


<script class="init">
    var submenu;
    @if (ViewBag.Method == 1)
    {
        <text>submenu = "新采购单";</text>
    }
    else if (ViewBag.Method == 2)
    {
        <text>submenu = "新销售单";</text>
    }
    else if (ViewBag.Method == 3)
    {
        <text>submenu = "采购退货";</text>
    }
    else if (ViewBag.Method == 4)
    {
        <text>submenu = "销售退货";</text>
    }
    LocatedMenu("交易管理", submenu);
    $("#txtNoteDate").kendoDatePicker({
        value: new Date(),
        culture: "zh-CHS",
        format: "yyyy年MM月dd日",
    });

    var allCustomer = Whale.Remote.GetEntity({
        url: "/Members/Customer/Gets",
        parameters: {
            cType: "@(ViewBag.Method % 2 == 0 ? 1 : 2)",
            customerStatus:1
        }
    });
    $("#txtCustomer").kendoComboBox({
        autoBind:false,
        placeholder: "请选择客户...",
        filter: "contains",
        dataTextField: "PinYinAndMobile",
        template: "#=ComplexName#",
        dataValueField: "ID",
        dataSource:allCustomer,
        change: function (e) {
            if ($.isNumeric(this.value())) {
                var item = this.dataItem();
                $("#txtCustomer").attr("data-value", item.ID);
                @if (ViewBag.Method == (int)LuxDiner.Model.Orders.OrderMethod.XS)
                {
                     <text>
                $("#txtAddress").val(item.Address);
                $("#txtRealName").val(item.RealName);
                $("#txtMobile").val(item.Mobile);
                    </text>
                }
                this.text(item.ComplexName);
            }
        }
    });
</script>

<script class="grid_orders_columns">
    var orderFields = [{
        title: "商品名称",
        field: "Product",
        template: "#=Product.ProductName#",
        editor: productEditor,
        width: 200
    }, {
        title: "单位",
        field: "Unit",
        template: "#=Product.UnitName#",
        width: 100
    }, {
        title: "数量",
        field: "Quantity",
        editor: quantityEditor,
        width: 100
    }, {
        title: "辅助数量",
        field: "ShowUnit",
        width: 100
    }, {
        title: "单价",
        field: "UnitPrice",
        format: "{0:c5}",
        editor: priceEditor,
        width: 100
    }, {
        title: "金额",
        field: "Amount",
        format: "{0:c}",
        width: 100
   
    }, {
        title: "操作",
        command: [{
            name: "destroy",
            text: "删除"

        }]
    }];

    var allProducts = Whale.Remote.GetEntity({
        url: "/Products/Product/Gets",
        parameters: {
            pageSize: 0,
            productStatus:1
        }
    });
    function productEditor(container, options) {
        var selPro = $('<input required data-bind="value:Product.ProductName "/>')
            .appendTo(container)
            .kendoComboBox({
                autoBind: false,
                filter: "contains",
                dataTextField: "Pinyin",
                template: "#=ProductName#",
                dataValueField: "ID",
                dataSource: allProducts,
                change: function (e) {
                    if (selPro.dataItem() == null || selPro.dataItem() == undefined) {
                        $("#grid_orders").data("kendoGrid").cancelRow();
                        return;
                    }
                    var product = selPro.dataItem();
                    options.model.Product = product;


                    //#region 取最后一次交易的单价
                    if ($("#txtCustomer").attr("data-value") > 0) {
                        var price = Whale.Remote.GetEntity({
                            url: "/Orders/DealOrder/GetLastPrice",
                            parameters: {
                                customerID: $("#txtCustomer").attr("data-value"),
                                productID: product.ID
                            }
                        });
                        if (price > 0)
                            options.model.UnitPrice = price;
                    }
                    //#endregion

                    RefreshRow(options);
                }
            }).data("kendoComboBox");
    }

    //#region 过期代码
    //function unitEditor(container, options) {
    //    var selUnit = $('<input required data-text-field="UnitName" data-value-field="ID" data-bind="value:' + options.field + '"/>')
    //        .appendTo(container)
    //        .kendoDropDownList({
    //            autoBind: false,
    //            dataSource: Whale.dataSource({
    //                url: "/Products/Unit/GetUnits",
    //                getParameters: function () {
    //                    return {
    //                        productID: options.model.Product.ID
    //                    };
    //                }
    //            }),
    //            change: function (e) {
    //                if (selUnit.dataItem() == null || selUnit.dataItem() == undefined)
    //                    return;
    //                options.model.Unit = selUnit.dataItem();
    //                RefreshRow(options);
    //            }
    //        }).data("kendoDropDownList");
    //}
    //#endregion
    function priceEditor(container, options) {
        var txtPrice = $('<input required data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoNumericTextBox({
                format: "{0:c}",
                decimals: 5,
                change: function (e) {
                    RefreshRow(options, txtPrice.value());
                }
            }).data("kendoNumericTextBox");
    }

    var units = [];
    function quantityEditor(container, options) {
        var txtQuantity = $('<input required data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoNumericTextBox({
                decimals: 3,
                change: function (e) {
                    GetShowUnit(options);
                    RefreshRow(options, options.model.UnitPrice, txtQuantity.value());
                }
            }).data("kendoNumericTextBox");
    }

    function GetShowUnit(options) {
        if (options.model.Product.ID > 0) {
            var rate = options.model.Product.AssistantUnitRate;
            if (rate != null && rate > 0) {
                var q = options.model.Quantity;
                var d = Math.floor(q / rate);
                var m = q % rate;
                if (d > 0) {
                    options.model.ShowUnit = d + options.model.Product.AssistantUnitName;
                    if (m > 0)
                        options.model.ShowUnit += m + options.model.Product.UnitName;
                    return;
                }
            }
        }
        options.model.ShowUnit = "";
    }

    function RefreshRow(options, price, quantity) {
        if (options != undefined) {
            if (price != undefined)
                options.model.UnitPrice = price;
            //else
            //    options.model.UnitPrice = options.model.Unit.UnitPrice;
            if (quantity != undefined)
                options.model.Quantity = quantity;
            options.model.Amount = options.model.UnitPrice * options.model.Quantity;
        }

        $("#grid_orders").data("kendoGrid").refresh();
        var sum = 0;
        $.each(orderDataSource.data(), function (i, o) {
            sum += o.Amount;
        });
        $("#lblSum").html(kendo.toString(sum, "c"));
    }
</script>

<script class="grid_orders_dataSource">
    var orderDataSource = new kendo.data.DataSource({
        schema: {
            model: {
                fields: {
                    Product: { defaultValue: { ID: 0, ProductName: "", UnitName: "" } },
                    Quantity: { validation: { required: true } },
                    Amount: { editable: false, type: "number" },
                    UnitPrice: { validation: { required: true } },
                    Unit: { editable: false },
                    ShowUnit: { editable: false }
                }
            }
        },
        change: function (e) {
            if (e.action == "remove") {
                RefreshRow();
            }
        }
    });
</script>

<script class="grid_orders_config">
    $("#grid_orders").kendoGrid({
        columns: orderFields,
        pageable: false,
        toolbar: [{
            name: "create",
            text: "新增一行"
        }, {
            name: "save",
            text: "保存单据"
        }],
        editable: true,
        dataBound: function (e) {
            //让表头居中
            $("th.k-header").attr("style", "text-align:center; font-weight:bold;");
            $("a.k-grid-save-changes").attr("style", "font-weight:bold; float:right");
        },
        dataSource: orderDataSource,
        saveChanges: function (e) {
            var values = {
                orderDate: kendo.toString($("#txtNoteDate").data("kendoDatePicker").value(), "yyyy-MM-dd"),
                customerID: $("#txtCustomer").attr("data-value"),
                method: "@ViewBag.Method",
                description:$("#txtDescription").val(),
                orderItems: []
                @if (ViewBag.Method == (int)LuxDiner.Model.Orders.OrderMethod.XS)
                {
                     <text>
                        , delivers: "地址：" + $("#txtAddress").val() + " 收货人:" + $("#txtRealName").val() + " 手机:" + $("#txtMobile").val()
                    </text>
                }
            };
            values.orderItems = $.map(orderDataSource.data(), function (o) {
                return {
                    productID: o.Product.ID,
                    quantity: o.Quantity,
                    unitPrice: o.UnitPrice
                }
            });
            Whale.Remote.Operation({
                url: "/Orders/DealOrder/SaveOrders",
                parameters: values,
                success: function (result) {
                    location.href = "/Success/PrintDealOrder/" + result.OrderNo;
                },
                error: function (msg) {
                    wndGeneralInformation.content(msg).open();
                }
            });
        }
    });
</script>
